import React, {Component} from "react";
import {connect} from 'react-redux'
import ReactDOM from "react-dom";
import {Modal, Input, Form, Switch, Button, Icon, message} from "antd";
import {messages} from "share/common";
import QuickReply from "components/template/quick-reply";
import auditService from "../finance-audit.service";
import "styles/financial-management/new-finance-audit/components/modal-remove-from-bag.scss"
import "styles/financial-management/new-finance-audit/components/modal-delete-confirm.scss"

const TextArea = Input.TextArea;
const FormItem = Form.Item;

@Form.create()
@connect(mapStateToProps)
class ModalRemoveFromBag extends Component {

  state = {
    needReject: JSON.parse(localStorage.getItem(`remove-from-bag-and-reject`) || 'true'),
    paperModalVisible: false,
    reason: '',
    attachmentOIDs: [],
    loading: false,
  };

  handleSwitchChange = enabled => {
    localStorage.setItem(`remove-from-bag-and-reject`, enabled);
    this.setState({ needReject: enabled });
  };

  handleImageUpload = attachments => {
    this.setState({ attachmentOIDs: attachments.map(a => a.attachmentOID) })
  };

  handlePaperBack = paperBack => {
    this.setState({ paperModalVisible: false });
    this.handleOk(paperBack,true);
  };

  handleOk = (paperBack, ignorePaper) => {
    const { info: { expenseReportOID }, loginUser: { userOID }, options: { auditBaseConfig } } = this.props;
    const { needReject, attachmentOIDs } = this.state;
    let params = {
      expenseReportOID,
      operator: userOID,
      auditReject: needReject
    };
    // 从发票袋移除并驳回单据
    if (needReject) {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          params.approvalTxt = values.reason;
          params.attachmentOIDs = attachmentOIDs;
          params.needChargeBack = paperBack;
          if ((auditBaseConfig.reviewExpBeforeReceive) && !ignorePaper) {
            this.setState({ paperModalVisible: true });
          } else {
            this.deleteRelation(params);
          }
        }
      })
    }
    // 从发票袋移除
    else {
      this.deleteRelation(params);
    }
  };

  deleteRelation = params => {
    this.setState({ loading: true });
    auditService.deleteBagRelation(params)
      .then(() => {
        message.success(messages('common.operate.success')/*操作成功*/);
        this.handleCancel(true, params.auditReject);
      })
      .finally(() => this.setState({ loading: false }))
  };

  handleCancel = (refresh, needBack) => {
    this.props.onClose();
    refresh && this.props.afterClose(needBack);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { visible, reason } = this.props;
    const { needReject, paperModalVisible, loading } = this.state;
    return (
      <Modal
        visible={visible}
        title={messages('expense-14.key497')/*从发票袋移除*/}
        className="modal-remove-from-bag"
        confirmLoading={loading}
        onOk={() => this.handleOk(false)}
        onCancel={() => this.handleCancel()}
      >
        <div>
          <span className="modal-remove-from-bag-reject">{messages('expense-14.key501')/*驳回单据*/}</span>
          <Switch
            checked={needReject}
            onChange={this.handleSwitchChange}
          />
        </div>
        {needReject && (<Form>
          <FormItem label="" colon={false}>
            {getFieldDecorator('reason', {
              rules: [{
                required: true,
                message: messages('common.please.input')/*请输入*/
              }, {
                max: 500,
                message: messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/
              }],
              initialValue: reason
            })(
              <QuickReply
                handleImageUpload={this.handleImageUpload}
                params={{ withAttachments: true, audit: true }}
              >
                <TextArea
                  rows={2}
                  placeholder={messages('expense-14.key253')/*请填写驳回理由*/}
                  style={{ resize: 'none', paddingBottom: 30 }}
                />
              </QuickReply>
            )}
          </FormItem>
        </Form>)}

        <Modal
          visible={paperModalVisible}
          className="modal-delete-confirm"
          width={350}
          closable
          onCancel={() => this.setState({ paperModalVisible:false })}
          footer={[
            <Button type="primary" onClick={() => this.handlePaperBack(true)}>
              {messages('expense-14.key31')/*驳回并退单*/}
            </Button>,
            <Button onClick={() => this.handleOk(false,true)}>
              {messages('common.reject')/*驳回*/}
            </Button>
          ]}
        >
          <div className="ant-confirm-body">
            <Icon type="question-circle" className="modal-delete-confirm-icon"/>
            <span className="ant-confirm-title">{messages('expense-14.key32')/*是否需要退回纸质单据？*/}</span>
          </div>
        </Modal>
      </Modal>
    );
  }
}

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
    options: state.login.options,
  }
}

ModalRemoveFromBag.open = function (config = {}, env) {
  let defaultConfig = {
    visible: false,
    onClose: close
  };
  let targetConfig = Object.assign(
    {},
    defaultConfig,
    config,
  );
  let div = document.createElement('div');
  let container = document.body;
  container.appendChild(div);
  function render(props) {
    if (env) {
      ReactDOM.unstable_renderSubtreeIntoContainer(env, <ModalRemoveFromBag {...props}/>, div, null)
    } else {
      ReactDOM.render(<ModalRemoveFromBag {...props}/>, div)
    }
  }
  function close() {
    if (div) {
      ReactDOM.unmountComponentAtNode(div);
      container.removeChild(div);
      div = null;
    }
  }
  render(targetConfig);
};

export default ModalRemoveFromBag;
